﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.IO;
using System.Drawing.Printing;

namespace CommonLibCore
{
    public class PrintOper
    {
        PrintDocument printDoc = new PrintDocument();
        string img = "";

        public void StartPring(string str)
        {
          
            printDoc.PrintController = new StandardPrintController();
            img = str;
            printDoc.PrintPage += printDocument1_PrintPage;
            printDoc.Print();
        }
        
        public  void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
        {
            Bitmap printImg = GeneralTools.Base64StringToImage(img);

            Graphics g = Graphics.FromImage(GeneralTools.Base64StringToImage(img));
            e.Graphics.DrawImage(GeneralTools.Base64StringToImage(img), 0, 0);


            //string fullName = lbPictureName.SelectedItem.ToString();     //图片的全名  
            //string fullPath = GetPictureFullPath(fullName);        //图片的全路径  
            int printWidth = printDoc.DefaultPageSettings.PaperSize.Width;   //打印机纸张的宽度  
            int printHeight = printDoc.DefaultPageSettings.PaperSize.Height;  //打印机纸张的高度  
            int picWidth = printImg.Width;    //图片的宽度  
            int picHeight = printImg.Height;  //图片的高度  
            //判断图片的宽度是否小于打印纸张的宽度  
            if (picWidth <= printWidth)  //如果图片的宽度小于或等于纸张的宽度，则让图片处于纸张正中间  
            {
                float x = (printWidth - picWidth) / 2;   //设置图片显示的水平位置  
                float y = (printHeight - picHeight) / 2; //设置图片显示的垂直位置  
                //使用DrawImage方法重新绘制图片  
                e.Graphics.DrawImage(printImg, x, y, picWidth, picHeight);
            }
            else
            {
                if (picWidth > printWidth)   //判断图片的宽度是否大于高度，如果大于，就把图片旋转90度显示  
                {
                    //Bitmap bm = printImg;  //以原图片路径创建一个新的图像  
                    //bm.RotateFlip(RotateFlipType.Rotate90FlipXY);     //把图片旋转90度  

                    ////计算图片高度占纸张宽度的比例  
                    //Single ratio = printWidth / picHeight;
                    //e.Graphics.DrawImage(bm, 0, 0, picHeight * ratio, picWidth * ratio);

                    Single ratio = picWidth / printWidth;
                    e.Graphics.DrawImage(printImg, 0, 0, printWidth * ratio, printHeight * ratio);
                }
                else    //如果图片宽度小于等于高度，就把图片按比例缩放显示  
                {
                    Single ratio = picWidth / printWidth;
                    e.Graphics.DrawImage(printImg, 0, 0, printWidth * ratio, printHeight * ratio);
                }
            }
        }
    }
}
